load inputdata

plot(dq,exp(yy))
title('Spot Price of Oil')
datetick('x');

% warning off
optz = optimset('fminunc');
optz = optimset(optz,'Display','off'); 
optz = optimset(optz,'Largescale','off'); 

%We use all oil prices since 1981 when Reagan deregulated the U.S. Oil
%Industry.  
zstart=  find(dq== datenum(1981,3,1));
stpoint = find(dq== datenum(1999,3,1));
enpoint = length(dq);
 
sv1 = [0   0.7126    0.0798    0.1556];
frbj = inline('[x(1:2) log(abs(x(3:4)))]','x');
revbj = inline('[x(1:2) exp(x(3:4))]','x');
% 
% bjalt =zeros(enpoint,4);
% for zx = enpoint:-1:stpoint;
%     bjll  = @(x) -ll([0 x], diff(yy(zstart:zx)));
%     sv = frbj(sv1);
%     bjbout  = fminunc(bjll ,sv(2:end), optz);
%     bjbout = revbj([0 bjbout]);
%     bjalt(zx,2:end) =  bjbout(:,2:end) ;
% end
% 
estval = nan(enpoint,3);

for zx = enpoint:-1:stpoint;
    
    rvll =   @(params)llfpermtempdecompdiff(diff(yy(zstart:zx)),params);
    rvbout = fminunc(rvll ,sv1(2:end),optz);
    estval(zx,:) = rvbout ;
    
end
varnam = char('\phi','\sigma_{p}','\sigma_{\tau}');

varp = estval(stpoint:enpoint,2).^2;
vart = estval(stpoint:enpoint,3).^2;
vartempcomp = vart.*((1-estval(stpoint:enpoint,1)).^2)./(1-estval(stpoint:enpoint,1).^2);
volshare  = nan(enpoint,1);
volshare(stpoint:enpoint) = varp./(varp+vart+vartempcomp);
plot(dq(stpoint:enpoint),volshare(stpoint:enpoint),'linewidth',3)
title('Fraction of Variance Due to Permanent Shocks','fontsize',18)
datetick('x');
